package com.xiao.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiao.wiki.domain.Category;
import com.xiao.wiki.domain.CategoryExample;
import com.xiao.wiki.mapper.CategoryMapper;
import com.xiao.wiki.req.CategoryQueryReq;
import com.xiao.wiki.req.CategorySaveReq;
import com.xiao.wiki.resp.CategoryQueryResp;
import com.xiao.wiki.resp.PageResp;
import com.xiao.wiki.util.CopyUtil;
import com.xiao.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ：降蓝
 * @description：TODO
 * @date ：2021/11/13 21:32
 */
@Service
public class CategoryService {

    private static final Logger LOG = LoggerFactory.getLogger(CategoryService.class);

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SnowFlake snowFlake;

    public List<CategoryQueryResp> all() {
        CategoryExample categoryExample = new CategoryExample();
        // 从数据库查询数据
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        List<CategoryQueryResp> categoryResps = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        return categoryResps;
    }

    public PageResp<CategoryQueryResp> list(CategoryQueryReq req) {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");

        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        // 从数据库查询数据
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        PageInfo<Category> categoryPageInfo = new PageInfo<>(categoryList);
        LOG.info("总行数：{}",categoryPageInfo.getTotal());
        LOG.info("总页数：{}",categoryPageInfo.getPages());


        PageResp<CategoryQueryResp> pageResp = new PageResp();
        // 将数据转换为响应需要的字段
        List<CategoryQueryResp> categoryResps = CopyUtil.copyList(categoryList, CategoryQueryResp.class);
        pageResp.setTotal(categoryPageInfo.getTotal());
        pageResp.setList(categoryResps);
        return pageResp;
    }

    /**
     * 保存
     */
    public void save(CategorySaveReq req) {
        Category category = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            //  新增
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        } else {
            //  更新
            categoryMapper.updateByPrimaryKey(category);
        }
    }

    /**
     * 删除
     */
    public void delete(Long id) {
            categoryMapper.deleteByPrimaryKey(id);
    }


}
